import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

function saveState(key, state) {
  localStorage.setItem(key, JSON.stringify(state))
}

function getState(key, defaultValue) {
  const data = localStorage.getItem(key)
  return data ? JSON.parse(data) : defaultValue
}

const user = {
  namespaced: true,
  state: {
    isLogin: getState('isLogin', false),
    username: getState('username', ''),
    users: getState('users', [
      // 默认内置一个测试用户
      { username: 'test', password: '123456' }
    ])
  },
  mutations: {
    login(state, username) {
      state.isLogin = true
      state.username = username
      saveState('isLogin', true)
      saveState('username', username)
    },
    logout(state) {
      state.isLogin = false
      state.username = ''
      saveState('isLogin', false)
      saveState('username', '')
    },
    register(state, { username, password }) {
      state.users.push({ username, password })
      saveState('users', state.users)
    }
  },
  actions: {
    login({ commit, state }, { username, password }) {
      return new Promise((resolve) => {
        const user = state.users.find(u => u.username === username && u.password === password)
        if (user) {
          commit('login', username)
          resolve(true)
        } else {
          resolve(false)
        }
      })
    },
    logout({ commit }) {
      return new Promise((resolve) => {
        commit('logout')
        resolve()
      })
    },
    register({ commit, state }, { username, password }) {
      return new Promise((resolve) => {
        if (state.users.find(u => u.username === username)) {
          resolve(false) // 用户已存在
        } else {
          commit('register', { username, password })
          resolve(true)
        }
      })
    }
  }
}

const settings = {
  namespaced: true,
  state: {
    theme: getState('theme', 'light')
  },
  mutations: {
    setTheme(state, theme) {
      state.theme = theme
      saveState('theme', theme)
    }
  },
  actions: {
    setTheme({ commit }, theme) {
      commit('setTheme', theme)
    }
  }
}

export default new Vuex.Store({
  modules: {
    user,
    settings
  }
}) 